import React, { useState } from 'react';
import { UserX, Plus, Edit2, Trash2, Upload, Calendar, Search } from 'lucide-react';

interface SpecialVisitor {
  id: string;
  name: string;
  phone: string;
  idCard: string;
  type: 'VIP' | '纠纷' | '其他';
  validUntil: string;
  notes: string;
  createdAt: string;
  updatedAt: string;
}

export const SpecialVisitors: React.FC = () => {
  const [visitors, setVisitors] = useState<SpecialVisitor[]>([
    {
      id: 'SV001',
      name: '王小明',
      phone: '13812345678',
      idCard: '110101199001011234',
      type: 'VIP',
      validUntil: '2024-12-31',
      notes: '重要客户，需特殊接待',
      createdAt: '2024-11-15 10:30:00',
      updatedAt: '2024-11-15 10:30:00'
    },
    {
      id: 'SV002',
      name: '张纠纷',
      phone: '13800138001',
      idCard: '110101198001011234',
      type: '纠纷',
      validUntil: '2025-01-31',
      notes: '存在医疗纠纷，需谨慎处理',
      createdAt: '2024-11-10 14:20:00',
      updatedAt: '2024-11-10 14:20:00'
    }
  ]);

  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const [showAddModal, setShowAddModal] = useState(false);
  const [editingVisitor, setEditingVisitor] = useState<SpecialVisitor | null>(null);

  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    idCard: '',
    type: 'VIP' as const,
    validUntil: '',
    notes: ''
  });

  const filteredVisitors = visitors.filter(visitor => {
    const matchesSearch = visitor.name.includes(searchTerm) || 
                         visitor.phone.includes(searchTerm) ||
                         visitor.idCard.includes(searchTerm);
    const matchesFilter = filterType === 'all' || visitor.type === filterType;
    return matchesSearch && matchesFilter;
  });

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'VIP':
        return 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200';
      case '纠纷':
        return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (editingVisitor) {
      // Update existing visitor
      setVisitors(visitors.map(visitor =>
        visitor.id === editingVisitor.id
          ? { ...visitor, ...formData, updatedAt: new Date().toLocaleString() }
          : visitor
      ));
      setEditingVisitor(null);
    } else {
      // Add new visitor
      const newVisitor: SpecialVisitor = {
        id: `SV${(visitors.length + 1).toString().padStart(3, '0')}`,
        ...formData,
        createdAt: new Date().toLocaleString(),
        updatedAt: new Date().toLocaleString()
      };
      setVisitors([newVisitor, ...visitors]);
    }
    
    setShowAddModal(false);
    setFormData({
      name: '',
      phone: '',
      idCard: '',
      type: 'VIP',
      validUntil: '',
      notes: ''
    });
  };

  const handleEdit = (visitor: SpecialVisitor) => {
    setEditingVisitor(visitor);
    setFormData({
      name: visitor.name,
      phone: visitor.phone,
      idCard: visitor.idCard,
      type: visitor.type,
      validUntil: visitor.validUntil,
      notes: visitor.notes
    });
    setShowAddModal(true);
  };

  const handleDelete = (id: string) => {
    if (confirm('确认删除该特殊访客记录？')) {
      setVisitors(visitors.filter(visitor => visitor.id !== id));
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      phone: '',
      idCard: '',
      type: 'VIP',
      validUntil: '',
      notes: ''
    });
    setEditingVisitor(null);
    setShowAddModal(false);
  };

  return (
    <div className="max-w-6xl mx-auto">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">特殊访客管理</h2>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                管理需要特殊关注的访客名单
              </p>
            </div>
            <div className="flex space-x-2">
              <button
                onClick={() => setShowAddModal(true)}
                className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
              >
                <Plus className="h-4 w-4 mr-2" />
                添加访客
              </button>
              <button className="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 transition-colors">
                <Upload className="h-4 w-4 mr-2" />
                批量导入
              </button>
            </div>
          </div>
        </div>

        <div className="p-6">
          {/* Search and filter */}
          <div className="flex flex-col sm:flex-row gap-4 mb-6">
            <div className="flex-1 relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center">
                <Search className="h-5 w-5 text-gray-400" />
              </div>
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                placeholder="搜索姓名、手机号或身份证号..."
              />
            </div>
            <select
              value={filterType}
              onChange={(e) => setFilterType(e.target.value)}
              className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              <option value="all">全部类型</option>
              <option value="VIP">VIP</option>
              <option value="纠纷">纠纷</option>
              <option value="其他">其他</option>
            </select>
          </div>

          {/* Visitor list */}
          {filteredVisitors.length === 0 ? (
            <div className="text-center py-12">
              <UserX className="mx-auto h-12 w-12 text-gray-400 mb-4" />
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                {searchTerm || filterType !== 'all' ? '没有找到匹配的记录' : '暂无特殊访客'}
              </h3>
              <p className="text-gray-600 dark:text-gray-400">
                {searchTerm || filterType !== 'all' 
                  ? '请尝试调整搜索条件或筛选器'
                  : '点击上方按钮添加第一个特殊访客记录'
                }
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {filteredVisitors.map((visitor) => (
                <div key={visitor.id} className="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition-shadow">
                  <div className="flex items-start justify-between">
                    <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <div className="flex items-center mb-2">
                          <span className="font-medium text-gray-900 dark:text-white text-lg">
                            {visitor.name}
                          </span>
                          <span className={`ml-3 px-2 py-1 text-xs rounded-full ${getTypeColor(visitor.type)}`}>
                            {visitor.type}
                          </span>
                        </div>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">
                          手机号：{visitor.phone}
                        </p>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mb-1">
                          身份证：{visitor.idCard}
                        </p>
                        <div className="flex items-center text-sm text-gray-600 dark:text-gray-400">
                          <Calendar className="h-3 w-3 mr-1" />
                          有效期至：{visitor.validUntil}
                        </div>
                      </div>
                      
                      <div>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">备注信息：</p>
                        <p className="text-sm text-gray-900 dark:text-white bg-gray-50 dark:bg-gray-700 p-2 rounded">
                          {visitor.notes || '无'}
                        </p>
                        <div className="text-xs text-gray-500 dark:text-gray-500 mt-2">
                          <div>创建：{visitor.createdAt}</div>
                          {visitor.updatedAt !== visitor.createdAt && (
                            <div>更新：{visitor.updatedAt}</div>
                          )}
                        </div>
                      </div>
                    </div>

                    <div className="flex space-x-2 ml-4">
                      <button
                        onClick={() => handleEdit(visitor)}
                        className="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded transition-colors"
                        title="编辑"
                      >
                        <Edit2 className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => handleDelete(visitor.id)}
                        className="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors"
                        title="删除"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Add/Edit Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-75 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 w-full max-w-2xl mx-4 max-h-screen overflow-y-auto">
            <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">
              {editingVisitor ? '编辑特殊访客' : '添加特殊访客'}
            </h3>
            
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    姓名 *
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({...formData, name: e.target.value})}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    required
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    手机号 *
                  </label>
                  <input
                    type="tel"
                    value={formData.phone}
                    onChange={(e) => setFormData({...formData, phone: e.target.value})}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    required
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    身份证号 *
                  </label>
                  <input
                    type="text"
                    value={formData.idCard}
                    onChange={(e) => setFormData({...formData, idCard: e.target.value})}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    required
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    类型 *
                  </label>
                  <select
                    value={formData.type}
                    onChange={(e) => setFormData({...formData, type: e.target.value as any})}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    required
                  >
                    <option value="VIP">VIP</option>
                    <option value="纠纷">纠纷</option>
                    <option value="其他">其他</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  有效期至 *
                </label>
                <input
                  type="date"
                  value={formData.validUntil}
                  onChange={(e) => setFormData({...formData, validUntil: e.target.value})}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  备注信息
                </label>
                <textarea
                  value={formData.notes}
                  onChange={(e) => setFormData({...formData, notes: e.target.value})}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  rows={3}
                  placeholder="请输入备注信息..."
                />
              </div>

              <div className="flex space-x-3 pt-4">
                <button
                  type="button"
                  onClick={resetForm}
                  className="flex-1 px-4 py-2 text-gray-700 dark:text-gray-300 bg-gray-200 dark:bg-gray-600 rounded-md hover:bg-gray-300 dark:hover:bg-gray-500 transition-colors"
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
                >
                  {editingVisitor ? '更新' : '添加'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};